package com.jet.chat.service;
import java.io.BufferedReader;
import java.io.PrintWriter;

import com.jet.chat.exception.ChatExceptionCheckAuthSQLException;
import com.jet.chat.exception.ChatExceptionMessageRead;


public class ChatAccessService {
	private DBService dbService;
	private int id;
	private String username;
	
	public ChatAccessService(DBService dbService) {
		this.dbService = dbService;
	}

	public void checkAuth(BufferedReader reader, PrintWriter writer) throws ChatExceptionMessageRead, ChatExceptionCheckAuthSQLException {
		ChatMessage chatMessage;
		int count = 0;
		while ( this.id == 0 && count < 3) {
			ChatMessageService.send(new ChatMessage("enter username"), writer);
			chatMessage = new ChatMessage(reader);
			username = chatMessage.getMessage();
			ChatMessageService.send(new ChatMessage("enter password"), writer);
			chatMessage = new ChatMessage(reader);
			String password = chatMessage.getMessage();
			
			this.id = dbService.checkAuth(username, password);
			
			if (this.id == 0) {
				chatMessage = new ChatMessage("wrong username-password. retype");
				ChatMessageService.send(chatMessage, writer);
			}
			
			count = count + 1;
		}
		
		if (count == 3) {
			chatMessage = new ChatMessage("three times with no valid. goodbye");
			ChatMessageService.send(chatMessage, writer);
			chatMessage = new ChatMessage("/q");
			ChatMessageService.send(chatMessage, writer);
		}
	}

	public int getId() {
		return id;
	}

	public String getUsername() {
		return username;
	}

}
